
package com.be.beadmin.quality.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.basicData.dto.output.UserEx;
import com.be.beadmin.basicData.entity.User;
import com.be.beadmin.basicData.service.UserService;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaQueryBuilderNew;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.product.entity.WorkOrderInfor_;
import com.be.beadmin.project.Util.MinioUtil;
import com.be.beadmin.project.controller.InfoController;
import com.be.beadmin.project.entity.Info;
import com.be.beadmin.project.service.InfoService;
import com.be.beadmin.quality.dto.input.ComplaintDetailsSimp;
import com.be.beadmin.quality.dto.input.ComplaintFileInfoDto;
import com.be.beadmin.quality.dto.input.CustomComplaintAllDto;
import com.be.beadmin.quality.dto.input.CustomComplaintDto;
import com.be.beadmin.quality.dto.output.CustomComplaintAllEx;
import com.be.beadmin.quality.dto.output.CustomComplaintEx;
import com.be.beadmin.quality.entity.ComplaintDetails;
import com.be.beadmin.quality.entity.ComplaintFileInfo;
import com.be.beadmin.quality.entity.CustomComplaint;
import com.be.beadmin.quality.entity.CustomComplaint_;
import com.be.beadmin.quality.mapper.CustomComplaintMapper;
import com.be.beadmin.quality.mapper.CustomComplaintMapperEx;
import com.be.beadmin.quality.repository.ComplaintDetailsRepository;
import com.be.beadmin.quality.repository.ComplaintFileInfoRepository;
import com.be.beadmin.quality.repository.CustomComplaintRepository;
import com.be.beadmin.quality.service.CustomComplaintService;
import com.be.beadmin.service.entity.NotifyInfo;
import com.be.beadmin.service.repository.NotifyInfoRepository;
import com.be.beadmin.service.repository.NotifyTemplateInfoRepository;
import com.be.beadmin.service.service.NotifyTemplateInfoService;
import com.be.beadmin.service.service.SerialNumberService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author zjm
 * @description 服务实现
 * @date 2023-05-15
 **/
@Service
@RequiredArgsConstructor
public class CustomComplaintServiceImpl implements CustomComplaintService {

    @Autowired
    private CustomComplaintRepository customComplaintRepository;
    @Autowired
    private CustomComplaintMapper customComplaintMapper;
    @Autowired
    private ComplaintDetailsRepository complaintDetailsRepository;
    @Autowired
    private ComplaintFileInfoRepository complaintFileInfoRepository;
    @Autowired
    private CustomComplaintMapperEx customComplaintExMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private SerialNumberService serialNumberService;
    @Autowired
    private InfoService infoService;
    MinioUtil minioUtil = new MinioUtil();

    @Autowired
    private NotifyTemplateInfoService notifyTemplateInfoService;

    @Autowired
    private NotifyTemplateInfoRepository notifyTemplateInfoRepository;

    @Autowired
    private NotifyInfoRepository notifyInfoRepository;

    @Override
    public Page<CustomComplaintEx> getCustomComplaintByPage(HttpServletRequest request , PageEntity pageEntity) {

        // 获取当前用户下的所有项目
        List<String> infoIds = infoService.getInfoIdByCurrentUser(request);
        // 判断角色
        // QM
        // 该角色的所有负责人
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() - 1,
                pageEntity.getPageSize());
        Page<CustomComplaint> page = customComplaintRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 = JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(CustomComplaint_.delete), 0); //过滤为0
                    list.add(pre2);

                    // 如果是系统管理员，所有的都可以看
                    if (!userService.isAdmin(request)) {

                        // 指定项目的工单
                        Path<String> path = root.get(CustomComplaint_.infoId);
                        CriteriaBuilder.In<String> in = criteriaBuilder.in(path);
                        for (String infoid : infoIds) in.value(infoid);
                        list.add(criteriaBuilder.and(in));

                        // QM都能看到
                        // 负责人只能看到自己负责的部分
                        if(!userService.isRole(request,"ROLE_Quality")) { // 不是质量经理就只能自己负责的部分
                            Predicate pre3 = criteriaBuilder.equal(root.get(CustomComplaint_.responsorId), userService.viewBaseInfo(request).getId()); //过滤为0
                            list.add(pre3);
                        }
                    }

                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if (pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(CustomComplaint_.createTime).as(Date.class)));
                    }
                    return criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        Page<CustomComplaintEx> page1 = page.map(customComplaintExMapper::toEntity);
        return page1;

    }
    @Override
    public void addCustomComplaint(CustomComplaintDto customComplaintDto) {
        CustomComplaint result = customComplaintRepository.findCustomComplaintByIdAndDelete(customComplaintDto.getId(), 0);
        if (ObjectUtil.isNotEmpty(result)) {
            throw new BeadminException("CustomComplaint不存在,请重新查询");
        }





        CustomComplaint customComplaint = customComplaintMapper.toEntity(customComplaintDto);
        customComplaintRepository.save(customComplaint);
    }

    @Override
    public void updateCustomComplaint(CustomComplaintDto customComplaintDto) {
        CustomComplaint customComplaint = customComplaintRepository.findCustomComplaintById(customComplaintDto.getId());
        //String customerName=customComplaintDto.getCustomerName();
        //String infoId=customComplaintDto.getInfoId();
        String makerId=customComplaintDto.getMakerId();
        String responsorId=customComplaintDto.getResponsorId();
        String ProblemTextDes=customComplaintDto.getProblemTextDes();
        Date makerTime=customComplaintDto.getMakerTime();
        Integer bugCount=customComplaintDto.getBugCount();
        String tempSolution=customComplaintDto.getTempSolution();
        String problemType=customComplaintDto.getProblemType();
//        if(customerName!=null && !Objects.equals(customerName, "")){
//            customComplaint.setCustomerName(customComplaintDto.getCustomerName());
//        }
//
//        if(infoId!=null && !Objects.equals(infoId,"")){
//            Info info=infoService.getInfoIdById(customComplaintDto.getInfoId());
//            customComplaint.setInfoId(info.getId());
//            customComplaint.setProjectCode(info.getProjectCode());
//            customComplaint.setProjectName(info.getProjectName());
//        }
        if(makerId!=null && !Objects.equals(makerId, "")){
            User user=userService.getUserById(makerId);
            customComplaint.setMakerId(user.getId());
            customComplaint.setMaker(user.getName());
        }
        if(responsorId!=null && !Objects.equals(responsorId,"")){
            User user = userService.getUserById(customComplaintDto.getResponsorId());
            customComplaint.setResponsorId(user.getId());
            customComplaint.setResponsor(user.getName());
        }
        if(ProblemTextDes!=null && !Objects.equals(ProblemTextDes,"")){
            customComplaint.setProblemTextDes(customComplaintDto.getProblemTextDes());
        }
        if(makerTime!=null ){
            customComplaint.setMakerTime(customComplaintDto.getMakerTime());
        }
        if(bugCount!=null && bugCount!=0){
            customComplaint.setBugCount(customComplaintDto.getBugCount());
        }
        if(tempSolution!=null && !Objects.equals(tempSolution,"")){
            customComplaint.setBugCount(customComplaintDto.getBugCount());
        }
        if(problemType!=null && !Objects.equals(problemType,"")){
            customComplaint.setProblemType(customComplaintDto.getProblemType());
        }
        //customComplaint = customComplaintMapper.toEntity(customComplaintDto);
        customComplaintRepository.save(customComplaint);
    }


    @Override
    public void delCustomComplaint(String id) {
        // 删除投诉信息
        CustomComplaint customComplaint = customComplaintRepository.findCustomComplaintById(id);
        customComplaint.setDelete(1);
        customComplaintRepository.save(customComplaint);

        // 删除每条问题
        List<ComplaintDetails> details = complaintDetailsRepository.findComplaintDetailsByComplaintIdAndDeleteOrderByQuestionNo(id, 0);
        details.forEach(detail -> detail.setDelete(1));
        complaintDetailsRepository.saveAll(details);

        // 删除每个附件
        List<ComplaintFileInfo> files=complaintFileInfoRepository.findComplaintFileInfosByComplaintIdAndDelete(id,0);
        files.forEach(file-> file.setDelete(1));
        complaintFileInfoRepository.saveAll(files);

    }

    /**
     * 删除多个角色
     *
     * @param ids
     */
    @Override
    public void delCustomComplaints(List<String> ids) {

    }


    /**
     * QM添加客户投诉信息
     *
     * @param
     */
    @SneakyThrows
    @Override
    public void addCustomComplaintByQm(HttpServletRequest request,String infoId, String customerName, String responsorId, int bugCount, String problemTextDes, String problemType,MultipartFile[] multipartFiles, String tempSolution,String bucketName,String makerId,Date makerTime) {
        // 投诉单的总体信息
//        CustomComplaintDto customComplaintDto = customComplaintAll.getCustomComplaintDto();

//        CustomComplaint result = customComplaintRepository.findCustomComplaintByIdAndDelete(customComplaintDto.getId(), 0);
//        if (ObjectUtil.isNotEmpty(result)) {
//            throw new BeadminException("CustomComplaint不存在,请重新查询");
//        }
        Info info = infoService.getInfoIdById(infoId);
        User user = userService.getUserById(responsorId);
        if (ObjectUtil.isEmpty(info)) {
            throw new BeadminException("项目不存在,error");
        }
        if (ObjectUtil.isEmpty(user)) {
            throw new BeadminException("负责人不存在,error");
        }
        //UserEx userCur = userService.viewBaseInfo(request);
        User maker=userService.getUserById(makerId);
        CustomComplaint customComplaint = new CustomComplaint();
        customComplaint.setInfoId(info.getId());
        customComplaint.setProjectName(info.getProjectName());
        customComplaint.setProjectCode(info.getProjectCode());
        customComplaint.setCustomerName(customerName);
        customComplaint.setResponsor(user.getName());
        customComplaint.setResponsorId(user.getId());

        customComplaint.setMakerId(maker.getId());
        customComplaint.setMaker(maker.getName());
        customComplaint.setMakerTime(makerTime);

        customComplaint.setResponsorId(user.getId());
        customComplaint.setBugCount(bugCount);
        customComplaint.setProblemTextDes(problemTextDes);
        customComplaint.setProblemType(problemType);
        customComplaint.setTempSolution(tempSolution);
        CustomComplaint saveCustomComplaint= customComplaintRepository.save(customComplaint);

        // 问题图片上传
        if (multipartFiles!=null) {
            for(MultipartFile file:multipartFiles) {
                ComplaintFileInfo complaintFile = new ComplaintFileInfo();
                complaintFile.setComplaintId(customComplaint.getId());
                complaintFile.setInfoId(info.getId());
                complaintFile.setState(0);

                complaintFile.setFileCode(serialNumberService.getNextSnByCode("FileCode"));
                complaintFile.setFileName(file.getOriginalFilename());
                complaintFile.setBucketName(bucketName);
                String uploadFileName=complaintFile.getFileCode()+"+"+complaintFile.getFileName();
                minioUtil.uploadFile(file,uploadFileName,bucketName);
                String fileUrl = minioUtil.getReadFile(bucketName,uploadFileName);
                complaintFile.setFileUrl(fileUrl);
                complaintFileInfoRepository.save(complaintFile);
//            customComplaint.setProblemPicFileCode(serialNumberService.getNextSnByCode("FileCode"));
//            customComplaint.setProblemPicFileName( multipartFile.getOriginalFilename());
//            customComplaint.setProblemPicBucketName(bucketName);
//            String uploadFileName = customComplaint.getProblemPicFileCode()+"+"+customComplaint.getProblemPicFileName();
//            minioUtil.uploadFile(multipartFile,uploadFileName,bucketName);
//
//            String fileUrl = minioUtil.getReadFile(bucketName,uploadFileName);
//            customComplaint.setProblemPicUrl(fileUrl);

            }

        }

        //-----------------------------------------------------------------------
        //发消息放最后
        // 客户投诉新增的提出人maker  发给  客户投诉中指定的负责人responsor，待办类型
        NotifyInfo notifyInfo =new NotifyInfo();
        notifyInfo.setModuleName("质量管理");
        notifyInfo.setFuncName("客户投诉");


        notifyInfo.setNotifyDesc("项目号为["+saveCustomComplaint.getProjectCode()+"],新增一条客户投诉需要您处理");
        notifyInfo.setNotifyType("待办");

        String senderName ="-";
        if(saveCustomComplaint.getMaker()!=null)senderName=saveCustomComplaint.getMaker();

        notifyInfo.setSenderName(senderName);
        notifyInfo.setSenderId(saveCustomComplaint.getMakerId());
        notifyInfo.setSendTime(saveCustomComplaint.getCreateTime());
        notifyInfo = notifyInfoRepository.save(notifyInfo);

        notifyTemplateInfoService.sendNotify(notifyInfo,-2,saveCustomComplaint.getResponsor(),saveCustomComplaint.getResponsorId());
        //发消息放最后
    }

    /**
     * 根据id获取客户投诉单
     *
     * @param id
     * @return
     */
    @Override
    public CustomComplaintAllEx getCustomComplaintById(String id) {
        // 获取投诉单的总体信息
        CustomComplaint customComplaintByIdAndDelete = customComplaintRepository.findCustomComplaintByIdAndDelete(id, 0);
        // 获取每一条信息
        List<ComplaintDetailsSimp> list = new ArrayList<>();
        for (ComplaintDetails complaintDetails : complaintDetailsRepository.findComplaintDetailsByComplaintIdAndDeleteOrderByQuestionNo(id, 0)) {
            ComplaintDetailsSimp simp = new ComplaintDetailsSimp();
            simp.setQuestionNo(complaintDetails.getQuestionNo());
            simp.setQuestion(complaintDetails.getQuestion());
            simp.setFeedback(complaintDetails.getFeedback());
            list.add(simp);
        }
        CustomComplaintAllEx customComplaintAllEx = new CustomComplaintAllEx();

        customComplaintAllEx.setCustomComplaintEx(customComplaintExMapper.toEntity(customComplaintByIdAndDelete));
        customComplaintAllEx.setComplaintDetailsList(list);

        return customComplaintAllEx;
    }

    /**
     * 更新该条客户投诉信息
     *
     * @param complaintAllDto
     * @return
     */
    @Override
    public int updateCustomComplaintAll(CustomComplaintAllDto complaintAllDto) {
        // 投诉单的总体信息
        CustomComplaintDto customComplaintDto = complaintAllDto.getCustomComplaintDto();

        // 更新了信息
        CustomComplaint customComplaint = customComplaintMapper.toEntity(customComplaintDto);
        customComplaintRepository.save(customComplaint);

        // 更新具体问题
        for (ComplaintDetailsSimp simp : complaintAllDto.getComplaintDetailsList()) {
            ComplaintDetails details = complaintDetailsRepository.findComplaintDetailsByComplaintIdAndQuestionNoAndDelete(customComplaintDto.getId(), simp.getQuestionNo(), 0);
            details.setQuestion(simp.getQuestion());
            complaintDetailsRepository.save(details);
        }

        return 0;
    }

    /**
     * 确认/完成客户投诉
     *
     * @param id
     */
    @Override
    public void finishCustomComplaint(String id) {
        CustomComplaint customComplaint = customComplaintRepository.findCustomComplaintById(id);
        customComplaint.setState(4);  //完成
        customComplaintRepository.save(customComplaint);
    }


    /**
     * 根据ID查看该条客户投诉信息new
     *
     * @param id
     * @return
     */
    @Override
    public CustomComplaintEx getCustomComplaintByIdNew(String id) {
        CustomComplaint result = customComplaintRepository.findCustomComplaintByIdAndDelete(id, 0);
        if (ObjectUtil.isEmpty(result)) {
            throw new BeadminException("CustomComplaint不存在,请重新查询");
        }
        return customComplaintExMapper.toEntity(result);
    }

    /**
     * 上传客户投诉信息
     *
     * @param complaintId
     */
    @Override
    public void submitCustomComplaint(String complaintId) {
        CustomComplaint result = customComplaintRepository.findCustomComplaintByIdAndDelete(complaintId, 0);
        if (ObjectUtil.isEmpty(result)) {
            throw new BeadminException("CustomComplaint不存在,请重新查询");
        }

        result.setState(1);
        customComplaintRepository.save(result);
    }

    /**
     * 关闭/确认客户投诉信息
     *
     * @param complaintId
     */
    @Override
    public void shutdownCustomComplaint(String complaintId,Date finishTime) {
        CustomComplaint result = customComplaintRepository.findCustomComplaintByIdAndDelete(complaintId, 0);
        if (ObjectUtil.isEmpty(result)) {
            throw new BeadminException("CustomComplaint不存在,请重新查询");
        }

        result.setState(4);
        result.setFinishTime(finishTime);
        CustomComplaint saveCustomComplaint = customComplaintRepository.save(result);

        //-----------------------------------------------------------------------
        //发消息放最后
        // 客户投诉的负责人responsor 发给  提出人maker ，通知类型
        NotifyInfo notifyInfo =new NotifyInfo();
        notifyInfo.setModuleName("质量管理");
        notifyInfo.setFuncName("客户投诉");

        notifyInfo.setNotifyDesc("项目号为["+saveCustomComplaint.getProjectCode()+"],您的一条客户投诉已被关闭");
        notifyInfo.setNotifyType("通知");

        String senderName ="-";
        if(saveCustomComplaint.getMaker()!=null)senderName=saveCustomComplaint.getResponsor();

        notifyInfo.setSenderName(senderName);
        notifyInfo.setSenderId(saveCustomComplaint.getResponsorId());
        notifyInfo.setSendTime(saveCustomComplaint.getUpdateTime());
        notifyInfo = notifyInfoRepository.save(notifyInfo);

        notifyTemplateInfoService.sendNotify(notifyInfo,-1,saveCustomComplaint.getMaker(),saveCustomComplaint.getMakerId());
        //发消息放最后
    }

    /**
     * 处理客户投诉信息 -- 负责人
     *
     * @param request
     * @param complaintId
     */
    @SneakyThrows
    @Override
    public void handleCustomComplaint(HttpServletRequest request, String complaintId,String reasonAnalysis,MultipartFile[] multipartFiles,String bucketName) {
        CustomComplaint result = customComplaintRepository.findCustomComplaintByIdAndDelete(complaintId, 0);
        if (ObjectUtil.isEmpty(result)) {
            throw new BeadminException("CustomComplaint不存在,请重新查询");
        }
        UserEx userEx = userService.viewBaseInfo(request);
        if (!userEx.getId().equals(result.getResponsorId())&& !userService.isAdmin(request)){
            throw new BeadminException("您不是负责人或者系统管理员，无法处理");
        }
        result.setReasonAnalysis(reasonAnalysis);
        if (multipartFiles != null ) {
            for(MultipartFile multipartFile:multipartFiles) {
                ComplaintFileInfo complaintFileInfo=new ComplaintFileInfo();
                complaintFileInfo.setComplaintId(complaintId);
                complaintFileInfo.setInfoId(result.getInfoId());
                complaintFileInfo.setFileCode(serialNumberService.getNextSnByCode("FileCode"));
                complaintFileInfo.setFileName(multipartFile.getOriginalFilename());
                complaintFileInfo.setBucketName(bucketName);

                String uploadFileName = complaintFileInfo.getFileCode() + "+" + complaintFileInfo.getFileName();
                minioUtil.uploadFile(multipartFile, uploadFileName, bucketName);
                String fileUrl = minioUtil.getReadFile(bucketName, uploadFileName);
                complaintFileInfo.setFileUrl(fileUrl);
                complaintFileInfo.setState(1);
                complaintFileInfoRepository.save(complaintFileInfo);
            }
        }
        result.setState(2);
        customComplaintRepository.save(result);

    }

    /**
     * QM分析 -- 该条客户投诉信息
     * @param request
     * @param complaintId
     * @param baseReasonAnalysis
     * @param improvementText
     */
    @SneakyThrows
    @Override
    public void analyzeCustomComplaintByQm(HttpServletRequest request, String complaintId, String baseReasonAnalysis, String improvementText) {
        CustomComplaint result = customComplaintRepository.findCustomComplaintByIdAndDelete(complaintId, 0);
        if (ObjectUtil.isEmpty(result)) {
            throw new BeadminException("CustomComplaint不存在,请重新查询");
        }
        result.setBaseReasonAnalysis(baseReasonAnalysis);
        result.setImprovementText(improvementText);
        result.setState(3);
        customComplaintRepository.save(result);
    }

    /**
     * @param customComplaintId
     * @return 投诉对应上传图片的地址
     */
    @SneakyThrows
    @Override
    public List<String> getFilePreviewUrl(String customComplaintId,String bucketName,Integer state){
        CustomComplaint customComplaint=customComplaintRepository.findCustomComplaintById(customComplaintId);
        List<ComplaintFileInfo> complaintInfos=null;
        List<String> urls=new ArrayList<String>();
        if (ObjectUtil.isEmpty(customComplaint)) {
            throw new BeadminException("CustomComplaint不存在,请重新查询");
        }
        complaintInfos=complaintFileInfoRepository.findComplaintFileInfosByComplaintIdAndAndState(customComplaint.getId(),state);

        for(ComplaintFileInfo complaintFileInfo:complaintInfos) {
            String previewUrl = minioUtil.getPreviewFileUrl(bucketName, complaintFileInfo.getFileCode()+"+"+complaintFileInfo.getFileName());
            urls.add(previewUrl);
        }
        return urls;

    }

}